package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.user.thread.AppThreadLocalUtil;
import com.heima.utils.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult login(LoginDto loginDto) {

        //1.判断入参是否为空
        if(loginDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.判断手机号和密码是否存在,如果为空,则为游客登录
        String phone = loginDto.getPhone();
        String password = loginDto.getPassword();
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(password)) {
            //为游客生成一个值为0的token
            String token = AppJwtUtil.getToken(0L);
            Map<String,Object> map = new HashMap<>(2);
            map.put("user",null);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }

        //3.如果都不为空则是用户登录,要验证phone的存在和密码的一致性
        //3.1先校验用户是否存在
        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUser::getPhone,phone);
        ApUser apUser = apUserMapper.selectOne(wrapper);
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //3.2再进行密码比对
        String salt = apUser.getSalt();
        //将传入密码与数据库中得到的salt拼接然后进行md5加密后与数据库中密码进行比对
        //注意密码与盐的拼接顺序
        String passwordAfterMd5 = DigestUtils.md5DigestAsHex((password+salt).getBytes());
        String userPassword = apUser.getPassword();
        if (!userPassword.equals(passwordAfterMd5)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //密码一致则生成token
        String token = AppJwtUtil.getToken(apUser.getId().longValue());

        Map<String,Object> map = new HashMap<>(2);
        //清空敏感数据再返回
        apUser.setPassword("");
        apUser.setSalt("");

        map.put("user",apUser);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult userFollow(UserRelationDto dto) {

        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //检测用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        Integer userId = user.getId();
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        Integer authorId = dto.getAuthorId();

        Short operation = dto.getOperation();
        if (operation == 0) {
            //向关注列表中添加数据
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, authorId.toString(), System.currentTimeMillis());
            //向粉丝列表中添加数据
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION + authorId, userId.toString(), System.currentTimeMillis());
        }else {
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + userId);
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + authorId);
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}